package com.newdjk.newdoctor;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.newdjk.newdoctor.entity.AppEntity;
import com.newdjk.newdoctor.fragment.FragmentController;
import com.newdjk.newdoctor.receiver.ExampleUtil;
import com.newdjk.newdoctor.service.MyService;
import com.newdjk.newdoctor.ui.LoginActivity;
import com.newdjk.newdoctor.utils.AppUpdateUtils;
import com.newdjk.newdoctor.utils.AuthService;
import com.newdjk.newdoctor.utils.Contants;
import com.newdjk.newdoctor.utils.Event;
import com.newdjk.newdoctor.utils.FragmentFactory;
import com.newdjk.newdoctor.utils.HomeUtils;
import com.newdjk.newdoctor.utils.RxBus;
import com.newdjk.newdoctor.utils.ToastUtil;
import com.newdjk.newdoctor.view.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class MainActivity extends BasActivity {

    private static final String TAG = "MainActivity";
    @BindView(R.id.view_pager)
    NoScrollViewPager viewPager;
    @BindView(R.id.iv_chat)
    ImageView ivChat;
    @BindView(R.id.tv_chat)
    TextView tvChat;
    @BindView(R.id.iv_contact)
    ImageView ivContact;
    @BindView(R.id.tv_contact)
    TextView tvContact;
    @BindView(R.id.iv_flow)
    ImageView ivFlow;
    @BindView(R.id.tv_flow)
    TextView tvFlow;
    @BindView(R.id.fl_red_dot)
    FrameLayout flRedDot;
    @BindView(R.id.im_me)
    ImageView imMe;
    @BindView(R.id.tabContainer)
    LinearLayout tabContainer;
    @BindView(R.id.system_unread_num)
    TextView systemUnreadNum;
    @BindView(R.id.system_unread_num_layout)
    LinearLayout systemUnreadNumLayout;


    private FragmentFactory fragmentFactory;
    private PagerAdapter mAdapter;
    private TabClickListener mTabClickListener;
    public static boolean isForeground = false;
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    public static final int REQUEST_CODE = 111;
    private List<Fragment> listFragment = new ArrayList();
    private FragmentController fgtController;
    private int mCustomVariable;
    private Observable<Integer> orderlistObservable;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        setStatusBarColor(this,R.color.transparent);
    }

    public static void setStatusBarColor(Activity activity, int colorId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = activity.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(activity.getResources().getColor(colorId));
            //更改状态栏文字文浅色
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }
    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!ExampleUtil.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e) {
            }
        }
    }

    private void setCostomMsg(String msg) {
        ToastUtil.setToast(msg + "发送数据到主界面");
    }

    @Override
    protected String setTitle() {
        return "工作台";
    }

    @Override
    protected int initViewResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, MyService.class));
        } else {
            startService(new Intent(this, MyService.class));
        }

        if (checkPermission()) {
            checkUpdate();
        }
        getBaiduToken();
        orderlistObservable = RxBus.get().register(Event.Order_list_count);

        orderlistObservable.observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer number) throws Exception {
                Log.d(TAG,"MessageFragment更新订单列表");
                if (number > 0) {
                    systemUnreadNum.setText(number + "");
                    systemUnreadNumLayout.setVisibility(View.VISIBLE);
                }else {
                    systemUnreadNumLayout.setVisibility(View.GONE);
                }
            }
        });
    }

    private void checkUpdate() {
        HomeUtils.INSTANCE.checkVersion(new HomeUtils.UpdateListener() {
            @Override
            public void success(final AppEntity entity) {
                AppUpdateUtils.mAppLicationUtils = null;
                AppUpdateUtils.getInstance().update(entity, MainActivity.this, MainActivity.this);

            }


            @Override
            public void failed(int statusCode, String errorMsg) {


            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        try {
            // checkUpdate();
        } catch (Exception e) {

        }
    }


    private boolean checkPermission() {

        List<String> permissions = new ArrayList<>();
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
            permissions.add(Manifest.permission.CAMERA);
        }

        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.ACCESS_FINE_LOCATION)) {
            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(MyApplication.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
            permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        int len = permissions.size();
        if (len != 0) {
            String[] per = new String[len];
            for (int i = 0; i < len; i++) {
                per[i] = permissions.get(i);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(
                        per,
                        REQUEST_CODE);
            }
            return false;
        }
        return true;

    }

    @Override
    protected void onPause() {
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void initView() {
        fragmentFactory = new FragmentFactory();
        viewPager.setOffscreenPageLimit(4);
        mAdapter = new PagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(mAdapter);

        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                pageSelected(position);
            }
        });
        pageSelected(0);

//        listFragment.add(fragmentFactory.createFragment(0));
//        listFragment.add(fragmentFactory.createFragment(1));
//        listFragment.add(fragmentFactory.createFragment(2));
//        listFragment.add(fragmentFactory.createFragment(3));
//        fgtController = new FragmentController(this, R.id.fl_main, listFragment);
//        fgtController.showFragment(0);
        tabContainer.getChildAt(0).setSelected(true);
        int tabCount = tabContainer.getChildCount();
        mTabClickListener = new TabClickListener();
        for (int i = 0; i < tabCount; i++) {
            View textView = tabContainer.getChildAt(i);
            textView.setOnClickListener(mTabClickListener);
        }
    }

    private void pageSelected(int position) {
        updateTabContainer(position);
        switch (position) {
            case 0:
                setNavTitle("工作台");
                break;
            case 1:
                setNavTitle("消息");
                break;
            case 2:
                setNavTitle("发现");
                break;
            case 3:
                setNavTitle("我的");
                break;

        }
    }

    //更新底部几个按钮状态
    private void updateTabContainer(int position) {

        for (int i = 0; i < tabContainer.getChildCount(); i++) {
            if (position == i) {
                tabContainer.getChildAt(i).setSelected(true);
            } else {
                tabContainer.getChildAt(i).setSelected(false);
            }
        }
    }

    private class PagerAdapter extends FragmentPagerAdapter {

        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {


            return fragmentFactory.createFragment(position);
        }

        @Override
        public int getCount() {
            return 4;
        }


    }

    private class TabClickListener
            implements View.OnClickListener {

        int selectedIndex = 0;

        @Override
        public void onClick(View v) {
            //如果切到第三页并且没有登录
            int tempSelectedIndex = tabContainer.indexOfChild(v);
            if (tempSelectedIndex == 3) {
                if (MyApplication.isLogin != true) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    intent.putExtra(Contants.toLogin, Contants.From_mainActivity);
                    startActivity(intent);
                    return;
                }
            }

            if (selectedIndex == tempSelectedIndex) {
                return;
            }

            if (selectedIndex >= 0 && selectedIndex < tabContainer.getChildCount()) {
                tabContainer.getChildAt(selectedIndex)
                        .setSelected(false);
            }


            v.setSelected(true);
            selectedIndex = tempSelectedIndex;
            switch (selectedIndex) {
                case 0:
                    setNavTitle("工作台");
                    break;
                case 1:
                    setNavTitle("消息");
                    break;
                case 2:
                    setNavTitle("发现");
                    break;
                case 3:
                    setNavTitle("我的");
                    break;

            }
            //  fgtController.showFragment(selectedIndex);

            viewPager.setCurrentItem(selectedIndex, false);
        }

        public void setSelected(int position) {
            int childCount = tabContainer.getChildCount();

            if (position < 0 || position >= childCount) {
                throw new IllegalArgumentException(
                        "position must be >= 0 and < mTabContainer's child size");
            }

            if (selectedIndex >= 0 && selectedIndex < childCount) {
                tabContainer.getChildAt(selectedIndex)
                        .setSelected(false);
            }

            tabContainer.getChildAt(position)
                    .setSelected(true);

            selectedIndex = position;
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(Event.Order_list_count, orderlistObservable);

    }

    private void getBaiduToken() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String baidutoken = AuthService.getAuth();
                Log.i("MainActivity", "baidutoken=" + baidutoken);
                MyApplication.baiduToken = baidutoken;
            }
        }).start();


    }
}